import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
// import echarts from 'echarts'
import base from './assets/js'
import { getToken } from '@/utils/auth'
import * as custom from './filters'
import './registerServiceWorker'
// import './plugins/element.js'
import './theme/global.less';
import './theme/index.css'
import Cookies from 'js-cookie'
import VueClipboard from 'vue-clipboard2'

// 引入表格模块
import FileSaver from "file-saver";
import XLSX from "xlsx";
import { Loading, MessageBox, Notification, Message } from 'element-ui';
import Element from 'element-ui'
import 'normalize.css/normalize.css'

const whiteList = ['/login', '/auth-redirect']
console.log("123",process.env)
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API || "http://localhost:8081/api/wbms/",
  withCredentials: true, // send cookies when cross-domain requests
  headers: { 'X-CSRF-TOKEN': Cookies.get('X-CSRF-TOKEN') },
  timeout: 5000 // request timeout
})

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return Promise.resolve(response.data);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    if (error && error.response && error.response.status) {
      switch (error.response.status) {
        case 403:
          Message.error('登录过期，请重新登录');
          store.dispatch('user/token_expire')
          setTimeout(() => {
            router.push(`/login?redirect=${router.currentRoute.fullPath}`)
          }, 1000);
          break;
        case 404:
          console.log(404)
          break;
        default:
          console.log(error.response.data.message)
      }
      return Promise.reject(error.response);
    }
  }
)

Vue.use(base)
Vue.use(Element)
Vue.use(Loading.directive);
Vue.use( VueClipboard)
Vue.prototype.$loading = Loading.service;
Vue.prototype.$msgbox = MessageBox;
Vue.prototype.$alert = MessageBox.alert;
Vue.prototype.$confirm = MessageBox.confirm;
Vue.prototype.$prompt = MessageBox.prompt;
Vue.prototype.$notify = Notification;
Vue.prototype.$message = Message;
Vue.prototype.axios = service
// Vue.prototype.$echarts = echarts
Vue.config.productionTip = false

Object.keys(custom).forEach(key => {
  Vue.filter(key, custom[key])
})

// 导出表格
Vue.prototype.exportExcel = function (val, el) {
  this.$nextTick(() => {
    // 从表生成工作簿对象
    let wb = XLSX.utils.table_to_book(document.querySelector(el));
    // 获取二进制字符串作为输出
    let wbout = XLSX.write(wb, {
      bookType: "xlsx",
      bookSST: true,
      type: "array"
    });
    try {
      FileSaver.saveAs(
        new Blob([wbout], { type: "application/octet-stream" }),
        // 设置导出文件名称
        "sheetjs.xlsx"
      );
    } catch (e) {
      if (typeof console !== "undefined") console.log(e, wbout);
    }
    this.pageSize = 10;
    return wbout;
  });
};



function fakeClick(obj) {
  var ev = document.createEvent("MouseEvents");
  ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  obj.dispatchEvent(ev);
}
Vue.prototype.exportTxt = function exportRaw(name, data) {
  var urlObject = window.URL || window.webkitURL || window;
  var export_blob = new Blob([data]);
  var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
  save_link.href = urlObject.createObjectURL(export_blob);
  save_link.download = name;
  fakeClick(save_link);
}

// 路由跳转
// to即将要跳转转的路由对象
// from当前导航正要离开的路由
router.beforeEach(async (to, from, next) => {
  document.title = to.meta.title
  document.me
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')

          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)

          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
    }
  }
})

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')